<template>
    <view
        style="position: fixed; width: 750rpx; background: #fff"
        :style="{ height: systemInfo.statusBarHeight + 'px' }"
    ></view>

    <div class="wrapper" :style="'top:' + systemInfo.statusBarHeight + 'px'">
        <div class="header">
            <view class="back_div">
                <image
                    class="back_img"
                    @tap="goBack()"
                    src="@/static/back_img.png"
                    mode=""
                ></image>
            </view>
            <input
                class="input"
                @input="onInput"
                placeholder="中文/拼音/首字母"
                v-model="data.searchValue"
            />
        </div>
        <scroll-view
            class="calendar-list"
            scroll-y="true"
            :scroll-into-view="data.scrollIntoId"
        >
            <view v-if="data.disdingwei" id="hot">
                <!-- 定位模块 -->
                <view class="dingwei">
                    <view class="dingwei_Tips"> 当前定位 </view>
                    <view class="dingwei_city d-flex a-center">
                        <view
                            v-if="data.position.code !== null"
                            class="dingwei_city_one"
                            style="margin-top: 0; margin-bottom: 0"
                            @tap="back_city(data.position)"
                        >
                            <i class="tmicon tmicon-position-fill"></i>
                            {{ data.position.cityName }}
                        </view>
                        <view v-if="data.position.code == null" class="failed">
                            {{ data.position.cityName }}
                        </view>
                        <view class="dingweis_div" @tap="getWarpweft">
                            <image
                                class="dingweis"
                                src="@/static/dingweis.png"
                                mode=""
                            ></image>
                            <text>{{ data.po_tips }}</text>
                        </view>
                    </view>
                    <view class="dingwei_Tips" style="margin-top: 20rpx"
                        >热门城市</view
                    >
                    <view class="dingweiContent d-flex wrap">
                        <view
                            class="dingwei_city_one toright"
                            @tap="back_city(data.all)"
                        >
                            {{ data.all.cityName }}
                        </view>

                        <view
                            class="dingwei_city_one toright"
                            v-for="(item, index) in hotCity"
                            @tap="back_city(item)"
                        >
                            {{ item.cityName }}
                        </view>
                    </view>
                </view>

                <!-- 最近模块 -->
                <!-- <view class="dingwei" v-if="data.Visit.length >= 0">
                    <view class="dingwei_Tips"> 最近访问 </view>
                    <view class="dingweiContent d-flex wrap">
                        <view
                            class="dingwei_city_one toright"
                            v-for="(item, index) in data.Visit"
                            @tap="back_city(item)"
                        >
                            {{ item.cityName }}
                        </view>
                    </view>
                </view> -->
            </view>

            <!-- 城市列表 -->
            <view
                v-if="data.searchValue == ''"
                v-for="(item, index) in data.list"
                :id="getId(index)"
                :key="index"
                style="margin-top: 20rpx"
            >
                <view class="letter-header">{{ getId(index) }}</view>
                <view
                    class="city-div"
                    v-for="(city, i) in item"
                    :key="i"
                    @tap="back_city(city)"
                >
                    <text class="city">{{ city.cityName }}</text>
                </view>
            </view>
            <!-- 搜索结果 -->
            <view
                class="city-div"
                v-for="(item, index) in data.searchList"
                @tap="back_city(item)"
            >
                <text class="city">{{ item.cityName }}</text>
            </view>
        </scroll-view>

        <!-- 右侧字母 -->
        <view class="letters" v-if="data.searchValue == ''">
            <view class="letters-item" @tap="scrollTo('hot')">最近</view>
            <view
                class="letters-item"
                v-for="item in data.letter"
                :key="item"
                @tap="scrollTo(item)"
                >{{ item }}</view
            >
        </view>

        <!-- 选中之后字母 -->
        <view class="mask" v-if="data.showMask">
            <view class="mask-r">{{ data.selectLetter }}</view>
        </view>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { onReady, onShow } from "@dcloudio/uni-app";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { position as positionStore } from "@/store/position";
import { selectedCity as selectedCityStore } from "@/store/selectedCity";
import { getCityMsg } from "@/api/api";
import permision from "@/utils/permission.ts";
// import pinyin from "pinyin";

const systemInfo: any = systemInfoStore();
const selectedCity: any = selectedCityStore();
const position: any = positionStore();

import Citys from "@/const/city.js";

// import sss from "@/const/sss.json";

// sss.forEach(item=>{
//     const arr = pinyin(item.city,{style:'normal'})
//     const pyArr = pinyin(item.city,{style:'first_letter'})
//     item.pinyin = arr.join('');
//     item.py = pyArr.join('');
// })

// sss.sort((a,b)=>{
//     return a.py.localeCompare(b.py);
// })

// const arrCity = sss.map(item=>{
//     return {
//         cityName:item.city,
//         code:item.code,
//         pinyin:item.pinyin,
//         py:item.py,
//     }
// })

const goBack = () => {
    uni.navigateBack();
};

const hotCity: any = reactive(Citys.hotCity);

const citys: any = reactive(Citys.cities);

const data: any = reactive({
    ImgUrl: "",
    letter: [],
    selectLetter: "",
    searchValue: "",
    scrollIntoId: "",
    list: [],
    tId: null,
    searchList: [],
    showMask: false,
    disdingwei: true,
    Visit: [], //最近访问
    position: {},
    longitude: "", //经度
    latitude: "", //纬度
    seconds: 3,
    po_tips: "重新定位",
    all: { cityName: "全国", code: 0 },
});

onMounted(() => {
    uni.getStorage({
        key: "Visit_key",
        success: function (res) {
            data.Visit = res.data;
        },
    });

    //获取city.js 的程序字母
    const mu = [
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
        "g",
        "h",
        "j",
        "k",
        "l",
        "m",
        "n",
        "p",
        "q",
        "r",
        "s",
        "t",
        "w",
        "x",
        "y",
        "z",
    ];
    const tmp = [];
    for (let i = 0; i < mu.length; i++) {
        let item: any = mu[i];
        for (let j = 0; j < citys.length; j++) {
            var py = citys[j].py;
            if (py.substring(0, 1) == item) {
                if (tmp.indexOf(item) == -1) {
                    data.list[i] = [citys[j]];
                    tmp.push(item);
                    data.letter.push(item.toUpperCase());
                } else {
                    data.list[i].push(citys[j]);
                }
            }
        }
    }
});

const query = (source: any, text: any) => {
    let res = [];
    res = source.filter((item: any) => {
        const arr: any = [];
        let isHave = false;
        Object.keys(item).forEach((prop) => {
            const itemStr = item[prop];
            isString(itemStr) &&
                itemStr.split(",").forEach((val) => {
                    arr.push(val);
                });
        });
        arr.some((val) => {
            isHave = new RegExp("^" + text).test(val);
            return isHave;
        });
        return isHave;
    });
    //console.log(JSON.stringify(res));
    return res;
};
const isString = (obj: any) => {
    return typeof obj === "string";
};

const onInput = (e) => {
    const value = e.detail.value.toLowerCase();
    console.log(value);
    if (value !== "" && citys && citys.length > 0) {
        const queryData = query(citys, String(value).trim());
        data.searchList = queryData;
        data.disdingwei = false;
    } else {
        data.searchList = [];
        data.disdingwei = true;
    }
};
const back_city = (item) => {
    if (item) {
        //this.$emit("back_city", item);
        //unshift 把数据插入到首位，与push相反
        selectedCity.setCity(item);
        //data.Visit.unshift(item);
        data.searchValue = "";
        data.disdingwei = true;
        //const arr = data.Visit;
        //数组去重
        // function distinct(arr) {
        //     let newArr = [];
        //     for (let i = 0; i < arr.length; i++) {
        //         if (newArr.indexOf(arr[i]) < 0) {
        //             newArr.push(arr[i]);
        //         }
        //     }
        //     return newArr;
        // }
        // data.Visit = distinct(arr);
        // console.log(data.Visit, "---最近访问");
        // uni.setStorage({
        //     key: "Visit_key",
        //     data: [],
        // });
        goBack();
    } else {
        //this.$emit("back_city", "no");
    }
};
const getWarpweft = async () => {

    console.log('getWarpweft')
    console.log('getWarpweft')
    console.log('getWarpweft')
    console.log('getWarpweft')

    if (uni.platform === "ios") {
        const auth = permision.judgeIosPermission("location");

        let str = "当前无位置使用权限";

        if (!auth) {
            uni.showModal({
                title: `无法获取您的位置`,
                content: `${str}，建议前往系统设置，允许应用访问[位置]`,
                showCancel: true,
                confirmText: "前往系统设置",
                cancelText: "取消",
                async success({ confirm, cancel }) {
                    if (confirm) {
                        permision.gotoAppPermissionSetting();
                    }
                },
            });
            return;
        }
    }


    if (uni.platform === "android") {
        console.log('aaaaaaaaaa')
        console.log('aaaaaaaaaa')
        console.log('aaaaaaaaaa')
        const res = await permision
            .requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION")
            .catch((err) => {
                console.log("eeeeeeeeee");
                console.log("eeeeeeeeee");
                console.log("eeeeeeeeee");
                console.log(err);
            });

        let str = "当前无位置使用权限";

        if (res !== 1) {
            uni.showModal({
                title: `无法获取您的位置`,
                content: `${str}，建议前往系统设置，允许应用访问[位置]`,
                showCancel: true,
                confirmText: "前往系统设置",
                cancelText: "取消",
                async success({ confirm, cancel }) {
                    if (confirm) {
                        permision.gotoAppPermissionSetting();
                    }
                },
            });
            return;
        }
    }


    data.po_tips = "定位中...";
    uni.getLocation({
        type: "wgs84",
        async success(res) {
            console.log("当前位置的经度：" + res.longitude);
            console.log("当前位置的纬度：" + res.latitude);
            data.longitude = res.longitude;
            data.latitude = res.latitude;
            const longitude = res.longitude;
            const latitude = res.latitude;

            position.setPosition({ longitude, latitude });

            const result: any = await getCityMsg({ longitude, latitude });

            const {
                flag,
                data: { code },
            } = result;

            if (flag !== 1) {
                data.position = {
                    cityName: "定位失败",
                    code: null,
                };

                return;
            }

            let str = code + "";

            if (str.length === 6) {
                str = str.substr(0, 4) + "00";
            }

            for (let i = 0; i < citys.length; i++) {
                const city = citys[i];
                if (city.code === Number(str)) {
                    data.position = city;
                    break;
                }
            }

            setTimeout(() => {
                data.po_tips = "重新定位";
            }, 500);
        },
        fail(err) {
            console.log(err);
            setTimeout(() => {
                data.po_tips = "重新定位";
            }, 500);
            setTimeout(() => {
                getWarpweft();
            }, 2000);
        },
    });
};
const getId = (index: number) => {
    return data.letter[index];
};

const scrollTo = (letter: any) => {
    data.showMask = true;
    data.selectLetter = data.letter == "hot" ? "最" : letter;
    setTimeout(() => {
        data.showMask = false;
    }, 300);
    data.scrollIntoId = letter;
};

onReady(() => {});

onShow(() => {
    getWarpweft();
    //checkNet();
});
</script>

<style lang="scss" scoped>
.wrapper {
    position: fixed;
    z-index: 999999;
    background: #ffffff;
    height: 100%;
    width: 100%;
    top: 0px;
    left: 0px;
}

.mask {
    position: absolute;
    bottom: 0upx;
    top: 83upx;
    left: 0upx;
    right: 0upx;
    width: 750upx;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0);
}

.mask-r {
    height: 120upx;
    width: 120upx;
    border-radius: 60upx;
    display: flex;
    background: rgba(0, 0, 0, 0.5);
    justify-content: center;
    align-items: center;
    font-size: 40upx;
    color: #ffffff;
}

.content {
    height: 100%;
    width: 100%;
    background-color: #ffffff;
}

.header {
    height: 85upx;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.back_div {
    width: 65upx;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.back_img {
    width: 35upx;
    height: 35upx;
}

.input {
    font-size: 28upx;
    width: 620upx;
    height: 55upx;
    border-radius: 40upx;
    background-color: #f5f5f5;
    padding-left: 20upx;
    padding-right: 20upx;
    box-sizing: border-box;
}

.title {
    font-size: 30upx;
    color: white;
}

.show {
    left: 0;
    width: 100%;
    transition: left 0.3s ease;
}

.hide {
    left: 100%;
    width: 100%;
    transition: left 0.3s ease;
}

.title {
    font-size: 30upx;
    color: white;
}

.calendar-list {
    position: absolute;
    top: 83upx;
    bottom: 0upx;
    width: 100%;
    background-color: #ffffff;
}

.letters {
    position: absolute;
    right: 20rpx;
    bottom: 0px;
    width: 50upx;
    top: 260upx;
    color: #2f9bfe;
    text-align: center;
    font-size: 24upx;
}

.letters-item {
    margin-bottom: 5upx;
}

.letter-header {
    width: 660upx;
    height: 45upx;
    font-size: 22upx;
    color: #39393b;
    padding-left: 40rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    background-color: #ebedef;
}

.city-div {
    width: 660upx;
    height: 85upx;
    border-bottom-width: 0.5upx;
    border-bottom-color: #ebedef;
    border-bottom-style: solid;
    display: flex;
    align-items: center;
    margin-right: 35upx;
    padding-left: 40rpx;
}

.city {
    font-size: 28upx;
    color: #000000;
}

.dingwei {
    width: 100%;
    padding-top: 25upx;
    box-sizing: border-box;
    margin-bottom: 20;
}

.dingwei_Tips {
    margin-left: 24upx;
    margin-bottom: 24upx;
    font-size: 24upx;
    color: #a5a5a5;
}

.dingwei_city {
    padding-left: 20rpx;
    width: 660upx;
    height: 60upx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
}

.dingweiContent {
    padding: 0 20rpx;
}

.dingwei_city_one {
    padding: 10rpx;
    background-color: #f5f5f5;
    border-radius: 10rpx;
    font-size: 26rpx;
    color: #39393b;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 140rpx;
    margin-bottom: 20rpx;
    .tmicon {
        color: $slim-main;
    }
}

.failed {
    font-size: 24rpx;
    color: #fd5745;
}

.dingweis_div {
    display: flex;
    align-content: flex-end;
    align-items: center;
    height: 100%;
    font-size: 24rpx;
    color: #fd5745;
}

.dingweis {
    width: 32upx;
    height: 32upx;
}

.dingwei_city_zuijin {
    display: flex;
    justify-content: flex-start;
}

.toright {
    margin-right: 25upx;
}
</style>
